<?php
/**
 * author  :  hation
 *  email  : 331596350@qq.com
 * datetime: 2018/1/11 22:10
 */

namespace App\Http\Controllers\DepartmentManagement;

use App\Http\Controllers\CommonController;
use App\Models\Admin;
use App\Models\Files;
use App\Models\Ipbuy;
use App\Models\Operation;
use App\Models\ProgressOperatorRelation;
use App\Models\Product;
use App\Models\Progress;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Request;
use GuzzleHttp\Client;


/**
 * 业务部管理控制器
 * Class BusinessManagementController
 * @package App\Http\Controllers\DepartmentManagement
 */
class BusinessManagementController extends CommonController
{
    protected $pageNum = 15;
    protected $admin_table = "admin";

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 业务部人员登录界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
        return view('departmentManagement/business/login');
    }

    public function loginOut()
    {
        session()->flush();
        return Redirect::to('management/business/login');
    }

    public function getClaimCount()
    {
        $params['claim_state'] = config('config.claim_state.init');
        return Progress::with(['Product', 'FirstType'])
            ->where($params)
            ->count();
    }

    public function getDeleteCount()
    {
        $bid = Session::get('bid');
        $where_progress=[
            "admin_id"=>$bid
        ];
        $progressIds=ProgressOperatorRelation::onlyTrashed()->where($where_progress)->pluck("progress_id");
        $product=0;
        if(!empty($progressIds)){
            $progress = Progress::onlyTrashed()->whereIn( "id",$progressIds )->pluck( "product_id" );
            if (!empty( $progress )){
                $productId = array_unique( $progress->toArray() );

                $with    = [
                    "FirstType",
                    "User",
                ];
                $product = Product::onlyTrashed()->whereIn( "id",$productId )
                    ->count();
            }
        }

        return $product;

    }

    public function getReplyNotice()
    {
        return Product::with(['Progress', 'FirstType', 'User'])
            ->where(['is_download_notice' => 3])
            ->count();
    }

    /**
     * 登录处理逻辑
     * @return string
     */
    public function doLogin()
    {
        $request = Request::all();
        $params['account'] = $request['account'];
        $params['password'] = md5($request['password']);
        $params['type'] = config('config.management_flag.business');
        $re = Admin::where($params)->first();
        if (!empty(collect($re)->toArray())) {
            Session::put('bid', $re['id']);
            Session::put('bname', $re['real_name']);
            Session::put('real_name', $re['real_name']);
            return Redirect::to('management/business/index');
        } else {
            return error_return("登录失败");
        }
    }

    /**
     * 业务部管理员首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $bid = Session::get('bid');
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }
        $pids = ProgressOperatorRelation::where(['admin_id' => $bid])->pluck('progress_id');
        $product = Progress::with(['FirstType', 'Product', 'ProgressList'])
            ->whereIn('id', $pids)
            ->order()
            ->paginate($this->pageNum);

        $tab = $this->getNum(Session::get('bid'),$pids);
        $cancel = config('config.mission_state_map');
        $config = config('config.business_progress');
        $claimNum = $this->getClaimCount();
        $replyNum = $tab['businessReplyNum'];
        $deleteNum=$this->getDeleteCount();
        // dump($product);exit;

        $http = new Client();

        foreach($product->toArray()['data'] as $k=>$v){
            $url = 'http://10.10.80.254:22793/api/getContractStatus/'.$v['contract_id'];
//            $url = 'http://www.ipjoin.com/api/getContractStatus/'.$v['contract_id'];

            $response = $http->get($url);
            $api_data[$k] = json_decode((string)$response->getBody(), true);
        }
//        return $api_data;

        $data = ['product', 'config', 'cancel',  'claimNum', 'replyNum','deleteNum', 'tab' , 'api_data'];
        return view('departmentManagement/business/index', compact($data));
    }

//    public function indexSearch()
//    {
//        $request = Request::all();
//        $keywords = "";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $bid = Session::get('bid');
//        if (empty(Session::get('bid'))) {
//            return Redirect::to('management/business/login');
//        }
//        $pids = ProgressOperatorRelation::where(['admin_id' => $bid])->pluck('progress_id');
//        $product = Progress::with(['FirstType', 'Product', 'ProgressList'])
//            ->whereIn('id', $pids)
//            ->order()
//            ->paginate(0);
//        $tab = $this->getNum(Session::get('bid'),$pids);
//        $cancel = config('config.mission_state_map');
//        $config = config('config.business_progress');
//        $claimNum = $this->getClaimCount();
//        $replyNum = $tab['businessReplyNum'];
//        $deleteNum=$this->getDeleteCount();
//        $data = ['product', 'config', 'cancel',  'claimNum', 'replyNum','deleteNum', 'tab', 'keywords'];
//        return view('departmentManagement/business/indexSearch', compact($data));
//    }

    public function indexCertainSearch()
    {
        $applicant =Request::input('applicant');
        $company =Request::input('company');
        $first_type =Request::input('first_type');
        $is_renew =Request::input('is_renew');
        $number =Request::input('number');
        $created_at =Request::input('created_at');
       // dd($number);
        $bid = Session::get('bid');
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }
        $pids = ProgressOperatorRelation::where(['admin_id' => $bid])->pluck('progress_id');
//        dd($pids);
        $product = Progress::with(['FirstType', 'Product', 'ProgressList'])
            ->join('product','product.id','=','progress.product_id')
            ->whereIn('progress.id', $pids)
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($company , function ($query) use ($company) {
                return $query->where('product.company', $company );
            })
            ->when($first_type , function ($query) use ($first_type) {
                return $query->where('product.first_type_id', $first_type);
            })
            ->when($is_renew , function ($query) use ($is_renew) {
                return $query->where('progress.is_renew', $is_renew);
            })
            ->when($number, function ($query) use ($number) {
                return $query->where('product.phone',$number);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('progress.created_at','like','%'.$created_at.'%');
            })
            ->get();
        //dd($product);
        $tab = $this->getNum(Session::get('bid'),$pids);
        $cancel = config('config.mission_state_map');
        $config = config('config.business_progress');
        $claimNum = $this->getClaimCount();
        $replyNum = $tab['businessReplyNum'];
        $deleteNum=$this->getDeleteCount();
        $data = ['product', 'config', 'cancel',  'claimNum', 'replyNum','deleteNum', 'tab'];
        return view('departmentManagement/business/indexSearch', compact($data));
    }
    /**
     * @param $aid int 管理员id
     * @return array 业务部数量统计
     */
    public function getNum($aid,$pids)
    {
        $where = ['admin_id' => $aid];
        $tab = [];
        $tab['businessNum'] = ProgressOperatorRelation::where($where)
            ->count();
        $count = 0;
        $list = Progress::with(['Product' => function ($query) {
            $query->whereNotNull('file');
        }])
            ->where($where)
            ->get();
        foreach ($list as $v) {
            if (empty($v['Product'])) {
                $count++;
            }
        };
        $tab['businessFile'] = $count;
        $tab['businessUnsettled'] = Progress::where($where)
            ->whereNull('first_pay_time')
            ->count();
        $tab['businessTailPayment'] = Progress::whereIn('id',$pids)
            ->whereNull('tail_pay_time')
            ->count();
        $tab['businessFinish'] = Progress::whereIn('id',$pids)
            ->whereIn('state', [3, 4])
            ->count();
        $tab['businessReplyNum'] = $this->getReplyNotice();
        return $tab;
    }

    /**
     * 业务认领中心
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function claim()
    {
        //claim_state;
        $params['claim_state'] = config('config.claim_state.init');
        /* $product=ota(Product::with($with_product)
             ->paginate(1));*/
        $product = Progress::with(['Product', 'FirstType'])
            ->order()
            ->where($params)
            ->paginate($this->pageNum);
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=$this->getDeleteCount();
        //dump($product);exit;
        $data = ['product',  'claimNum', 'replyNum','deleteNum'];
        return view('departmentManagement/business/claim', compact($data));
    }

    public function claimSearch()
    {
        $request = Request::all();
        $keywords = "";
        if (isset($request['search'])) {
            $keywords = $request['search'];
        }
        $params['claim_state'] = config('config.claim_state.init');
        $product = Progress::with(['Product', 'FirstType'])
            ->order()
            ->where($params)
            ->paginate(0);
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=$this->getDeleteCount();
        $data = ['product', 'keywords',  'claimNum', 'replyNum','deleteNum'];
        return view('departmentManagement/business/claimSearch', compact($data));
    }

    /**
     * 业务认领逻辑
     */
    public function doClaim($id, $pid)
    {
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }
        $date = date("Y-m-d H:i:s");
        $item = Progress::find($pid);
        $item1 = Product::find($id);
        if (empty($item) || empty($item1)) {
            return error_return("暂无该条记录");
        }
        if ($item['is_cancel'] == config('config.mission_state_map.cancel')) {
            return error_return("任务已被取消，不能认领");
        }
        $item['claim_state'] = config('config.claim_state.business');
        $item['updated_at'] = $date;
        $item['admin_id'] = Session::get('bid');
        $item['agent'] = '业务部-' . Session::get('bname');
        $item1['updated_at'] = $date;
        if ($item->save() && $item1->save()) {
            $operation['product_id'] = $item['product_id'];
            $operation['operator_id'] = Session::get('bid');
            $operation['operator_type'] = config('config.operation_role.admin');
            $operation['content'] = '认领本次任务';
            $operation['operator_name'] = '业务部-' . Session::get('bname');
            $o['progress_id'] = $pid;
            $o['admin_id'] = Session::get('bid');
            $o['department_id'] = config('config.management_flag.business');
            $o['updated_at'] = $date;
            $o['created_at'] = $date;
            $o["process_id"]=$item[ 'id' ];
            $o["progress_list_id"]=$item[ 'progress_list_id' ];
            ProgressOperatorRelation::create($o)->save();
            addOperation($operation);
            return success_return('认领成功');
        } else {
            return error_return("认领失败");
        }
    }

    /**
     * 设置款项逻辑处理
     */
    public function setFund()
    {
        $request = Request::all();
        $date = date('Y-m-d H:i:s');
        $params1['price'] = $request['money-total'];
        $params1['first_payment'] = $request['money-first'];
        $params1['tail_payment'] = $request['money-end'];
        $id = $request['product'];
        $pid = $request['progress'];
        //dump($id);
        if (!$this->checkNum($params1['price']) || !$this->checkNum($params1['first_payment']) || !$this->checkNum($params1['tail_payment'])) {
            return error_return("款项格式错误");
        }
        if (bccomp(((float)$params1['first_payment'] + (float)$params1['tail_payment']), $params1['price']) != 0) {
            return error_return("款项设置错误");
        }
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }

        $params1['business_state'] = config('config.business_progress.unliquidated');
        $params['updated_at'] = $date;
        $params1['agent'] = '业务部-' . Session::get('bname');
        $item = Product::find($id);
        $item1 = Progress::find($pid);
        if (empty($item) || empty($item1)) {
            return error_return("暂无该条记录");
        }
        if ($item1['is_cancel'] == config('config.mission_state_map.cancel')) {
            return error_return("任务已被取消，不能操作");
        }
        foreach ($params as $k => $v) {
            $item[$k] = $v;
        }
        foreach ($params1 as $k => $v) {
            $item1[$k] = $v;
        }
        if ($item1->save() && $item->save() && !empty(Session::get('bid'))) {
            $d['product_id'] = $id;
            $d['operator_id'] = Session::get('bid');
            $d['operator_type'] = config('config.operation_role.admin');
            $d['content'] = "设置款项";
            $d['operator_name'] = '业务部-' . Session::get('bname');
            $d["process_id"]=$item1[ 'id' ];
            $d["progress_list_id"]=$item1[ 'progress_list_id' ];

            addOperation($d);
            return success_return('款项设置成功');
        } else {
            return error_return("款项设置失败");
        }
    }

    /**
     * 修改款项逻辑处理
     */
    public function editFund()
    {
        $request = Request::all();
        $date = date('Y-m-d H:i:s');
        $params1['price'] = $request['money-total'];
        $params1['first_payment'] = $request['money-first'];
        $params1['tail_payment'] = $request['money-end'];
        $id = $request['product'];
        $pid = $request['progress'];
        //dump($id);
        if (!$this->checkNum($params1['price']) || !$this->checkNum($params1['first_payment']) || !$this->checkNum($params1['tail_payment'])) {
            return error_return("款项格式错误");
        }
        if (bccomp(((float)$params1['first_payment'] + (float)$params1['tail_payment']), $params1['price']) != 0) {
            return error_return("款项设置错误");
        }
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }
        $params1['business_state'] = config('config.business_progress.unliquidated');
        $params1['agent'] = '业务部-' . Session::get('bname');
        $params['updated_at'] = $date;
        $item = Product::find($id);
        $item1 = Progress::find($pid);
        if (empty($item) || empty($item1)) {
            return error_return("暂无该条记录");
        }
        if ($item1['is_cancel'] == config('config.mission_state_map.cancel')) {
            return error_return("任务已被取消，不能操作");
        }
        foreach ($params as $k => $v) {
            $item[$k] = $v;
        }
        foreach ($params1 as $k => $v) {
            $item1[$k] = $v;
        }
        if ($item1->save() && $item->save()) {
            $d['product_id'] = $id;
            $d['operator_id'] = Session::get('bid');
            $d['operator_type'] = config('config.operation_role.admin');
            $d['content'] = "修改款项";
            $d['operator_name'] = '业务部-' . Session::get('bname');
            $d["process_id"]=$item1[ 'id' ];
            $d["progress_list_id"]=$item1[ 'progress_list_id' ];
            addOperation($d);
            return success_return('款项修改成功');
        } else {
            return error_return("款项修改错误");
        }
    }

    /**
     * 转接逻辑处理
     */
    public function transfer($id)
    {
        $date = date('Y-m-d H:i:s');
        $item = Progress::find($id);
        // dump($item);exit;
        if (empty($item)) {
            return error_return("暂无该条记录");
        }
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }
        if ($item['business_state'] != config('config.business_progress.first_pay_upload')) {
            return error_return("转接失败");
        }
        if ($item['is_cancel'] == config('config.mission_state_map.cancel')) {
            return error_return("任务已被取消，不能转接");
        }
        $item['business_state'] = config('config.business_progress.waiting_process');
        $item['updated_at'] = $date;
        if ($item->save()) {
            $d['product_id'] = $id;
            $d['operator_id'] = Session::get('bid');
            $d['operator_type'] = config('config.operation_role.admin');
            $d['content'] = "转接流程部";
            $d['operator_name'] = '业务部-' . Session::get('bname');
            $d["process_id"]=$item[ 'id' ];
            $d["progress_list_id"]=$item[ 'progress_list_id' ];
            addOperation($d);
            return success_return('转接成功');
        } else {
            return error_return("转接失败");
        }
    }

    /**
     * 通知书列表
     */
    public function applyNotice()
    {
        $product = Product::with(['Progress', 'FirstType', 'User'])
            ->whereIn('is_download_notice', [3, 4])
            ->paginate($this->pageNum);
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=$this->getDeleteCount();
        $data = ['product',  'claimNum', 'replyNum','deleteNum'];
        // dump($product);exit;
        return view('departmentManagement/business/apply-notice', compact($data));
    }

    public function applyNoticeSearch()
    {
        $request = Request::all();
        $keywords = "";
        if (isset($request['search'])) {
            $keywords = $request['search'];
        }
        $product = Product::with(['Progress', 'FirstType', 'User'])
            ->whereIn('is_download_notice', [3, 4])
            ->get();
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=$this->getDeleteCount();
        $data = ['product',  'claimNum', 'replyNum','deleteNum', 'keywords'];
        return view('departmentManagement/business/applyNoticeSearch', compact($data));
    }

    /**
     * 邮寄逻辑处理
     */
    public function doPost()
    {
        $request = Request::all();
        $id = $request['product'];
        $item = Product::find($id);
        // dump($item);exit;
        if (empty($item)) {
            return error_return("暂无该条记录");
        }
        if (empty(Session::get('bid'))) {
            return Redirect::to('management/business/login');
        }

        if ($item['is_download_notice'] == 3) {
            $item['is_download_notice'] = 4;
            $item['tracking_number'] = $request['courier_number'];
            if ($item->save()) {
                $d['product_id'] = $id;
                $d['operator_id'] = Session::get('bid');
                $d['operator_type'] = config('config.operation_role.admin');
                $d['content'] = "邮寄通知书";
                $d['operator_name'] = '业务部-' . Session::get('bname');
                $d["process_id"]=$item[ 'id' ];
                $d["progress_list_id"]=$item[ 'progress_list_id' ];
                addOperation($d);
                return success_return("邮寄成功");
            } else {
                return error_return("邮寄失败");
            }
        } else {
            return error_return("邮寄失败");
        }
    }

    public function userInfo()
    {
        $uid = Session::get('bid');
        $data = object_to_array(
            DB::table('admin')->where(array("id" => $uid))->first()
        );
        return view('departmentManagement/business/userInfo')->with('data', $data);
    }

    public function changePassword()
    {
        $uid = Session::get('bid');
        $pwd = object_to_array(DB::table('admin')->where(array("id" => $uid))->first());
        return view('departmentManagement/business/changePassword')->with('data', $pwd['password']);
    }

    public function doChangePassword()
    {
        $uid = Session::get('bid');
        $input = Request::all();
        if (empty($input['old_pwd'])) {
            return back()->with('error', '旧密码为空');
        } elseif (empty($input['new_pwd'])) {
            return back()->with('error', '新密码为空');
        } elseif (empty($input['require_pwd'])) {
            return back()->with('error', '确认密码为空');
        } else {
            $data['password'] = md5($input['require_pwd']);
            $res = DB::table('admin')->where(array("id" => $uid))->update($data);
            if ($res) {
                return back()->with('success', '密码修改成功');
            } else {
                return back()->with('error', '修改失败，请联系管理员');
            }
        }

    }


    /**
     * 校验是否是合法的非负浮点数
     * @param $num string 需要检验的串
     * @return int 1 yes 0 no
     */
    protected function checkNum($num)
    {
        return preg_match("/^\d+(\.\d+)?$/", $num);
    }




    public  function  deletedBusinessByUser(){

        $bid = Session::get('bid');
        if (empty($bid)) {
            return Redirect::to('management/business/login');
        }
        $where_progress=[
            "admin_id"=>$bid
        ];
        $progressIds=ProgressOperatorRelation::onlyTrashed()->where($where_progress)->pluck("progress_id");

        if(!empty($progressIds)){
            $progressIds=collect($progressIds)->toArray();
            $progress=Progress::onlyTrashed()->whereIn("id",$progressIds)->pluck("product_id");
            if(!empty($progress)){
               // dump($progress->toArray());die();

                $productId=array_unique($progress->toArray());

                $with=[
                    "FirstType",
                    "User",
                ];
                $product=Product::onlyTrashed()->with($with)
                    ->whereIn("id",$productId)
                    ->paginate($this->pageNum);

            }else{
                $product=[];
            }

        }else{
            $product=[];
        }
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=count(collect($product)->toArray()['data']);
        $deleteNum=$this->getDeleteCount();
        //dump($product);exit;
        $data = ['product',  'claimNum', 'replyNum','deleteNum'];

     //   dump(collect($product)->toArray());die();
        return view('departmentManagement/business/deletedBusinessByUser',compact($data));
        
    }


    public function deletedBusinessByUserSearch(){
        $bid = Session::get('bid');
        if (empty($bid)) {
            return Redirect::to('management/business/login');
        }
        $where_progress=[
            "admin_id"=>$bid
        ];

        $request = Request::all();
        $keywords="";
        if (isset($request['search'])) {
            $keywords = $request['search'];
        }

        $progressIds=ProgressOperatorRelation::onlyTrashed()->where($where_progress)->pluck("progress_id");

        if(!empty($progressIds)){
            $progressIds=collect($progressIds)->toArray();
            $progress=Progress::onlyTrashed()->whereIn("id",$progressIds)->pluck("product_id");
            if(!empty($progress)){
                // dump($progress->toArray());die();

                $productId=array_unique($progress->toArray());

                $with=[
                    "FirstType",
                    "User",
                ];
                $product=Product::onlyTrashed()->with($with)
                    ->whereIn("id",$productId)
                    ->paginate($this->pageNum);

            }else{
                $product=[];
            }

        }else{
            $product=[];
        }
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
       // $deleteNum=count(collect($product)->toArray()['data']);
        $deleteNum=$this->getDeleteCount();
        //dump($product);exit;
        $data = ['product',  'claimNum', 'replyNum','deleteNum','keywords'];

        //   dump(collect($product)->toArray());die();
        return view('departmentManagement/business/deletedBusinessByUserSearch',compact($data));

    }


    public function deletedBusiness($id){

       // $input = Request::all();
        $product_id=$id;
        if(!empty($product_id)){
            DB::beginTransaction();
             try{
                 Product::withTrashed()->where(["id"=>$product_id])->forceDelete();
                 $ids = Progress::withTrashed()->where(array('product_id' => $id))->pluck('id');
                 Progress::withTrashed()->where(["product_id"=>$product_id])->forceDelete();
                 ProgressOperatorRelation::withTrashed()->whereIn("id",$ids)->forceDelete();
                 Operation::withTrashed()->where(["product_id"=>$product_id])->forceDelete();
                 Files::withTrashed()->where(["product_id"=>$product_id])->forceDelete();
                 DB::commit();
             }catch(\Exception $e){
                 DB::callback();
                 return back()->with('error', '删除失败！未知错误');
             }

        }else{
            return back()->with('error', '删除失败！参数错误');
        }

    }


    public function recoverDeletedBusiness($id)
    {
        // $input = Request::all();
        $product_id=$id;
        if(!empty($product_id)){
            DB::beginTransaction();
            try{
                Product::where(["id"=>$product_id])->restore();
                $ids = Progress::where(array('product_id' => $id))->pluck('id');
               // dump(collect($ids)->toArray());die();
                Progress::where(["product_id"=>$product_id])->restore();
                ProgressOperatorRelation::whereIn("progress_id",collect($ids)->toArray())->restore();
                Operation::where(["product_id"=>$product_id])->restore();
                Files::where(["product_id"=>$product_id])->restore();
                DB::commit();
                return back()->with('success', '恢复成功');
            }catch(\Exception $e){
                DB::callback();
                return back()->with('error', '恢复失败！未知错误');
            }

        }else{
            return back()->with('error', '恢复失败！参数错误');
        }



    }
    /**
     * 设置/修改合同编号
     * @return int 1 yes 0 no
     */
    public function editContractId(){
        $info=Input::all();
        $contract=Progress::find($info['id']);
        $contract['contract_id']=$info['contractId'];
        $judg=$contract->save();
        if($judg)
            return back()->with('success', '合同编号设置成功');
        else
            return back()->with('error', '设置失败');
    }

    public function IpPurchase()
    {
        $product=Ipbuy::with(['FirstType','SecondType'])
            ->paginate($this->pageNum);
        $first_type = object_to_array(DB::table('first_type')->get(['id', 'name']));
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=$this->getDeleteCount();
        $data = ['product','first_type','claimNum','replyNum','deleteNum'];
        //dump($product);exit;
        return view('departmentManagement/business/IpPurchase', compact($data));
    }

    public function editProgress()
    {
        $input = Request::all();
        $id = $input['hide_id'];
        $data['progress'] = $input['edit_progress'];
        if (!empty($data)) {
            $res = DB::table('ipbuy')->where(array("id" => $id))->update($data);
            if ($res) {
                return back()->with('success', '修改成功');
            } else {
                return back()->with('error', '修改失败');
            }
        } else {
            return back()->with('error', '暂无数据');
        }
    }

    public function IpPurchaseCertain()
    {
        $request = Request::all();
        $uid=Session::get('uid');
        $first_type = $request['first_type'];
        $second_type = $request['second_type'];
        $name = $request['name'];
        $created_at = $request['created_at'];
        $progress = $request['progress'];
        $arr_province = ["不填","专利","商标","版权","项目"];
        $arr_second_type=config('config.arr_second_type');
        for ($j = 0;$j < sizeof($arr_second_type);$j++){
            if ($second_type == $arr_second_type[$j]){
                if ($j==0)
                    $j='';
                break;
            }
        }
        for ($i = 0;$i < 5;$i++){
            if ($first_type == $arr_province[$i]){
                if ($i==0)
                    $i='';
                break;
            }
        }
        $product=Ipbuy::with(['FirstType','SecondType'])
            ->when($i, function ($query) use ($i) {
                return $query->where('first_type', $i);
            })
            ->when($j, function ($query) use ($j) {
                return $query->where('second_type', $j);
            })
            ->when($name, function ($query) use ($name) {
                return $query->where('name', $name);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('created_at','like','%'.$created_at.'%');
            })
            ->when($progress, function ($query) use ($progress) {
                return $query->where('progress', $progress);
            })
            ->paginate($this->pageNum);
        $first_type = object_to_array(DB::table('first_type')->get(['id', 'name']));
        $claimNum = $this->getClaimCount();
        $replyNum = $this->getReplyNotice();
        $deleteNum=$this->getDeleteCount();
        $data = ['product','first_type','claimNum','replyNum','deleteNum'];
        //dump($product);exit;
        return view('departmentManagement/business/IpPurchaseCertain', compact($data));
    }
}




